package com.xjcs.saplingplan.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RadialGradient
import android.graphics.Shader
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.View
import com.xjcs.saplingplan.model.bean.BubbleBean
import java.util.Random
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt

class CustomBubbleView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val bubbles = mutableListOf<BubbleBean>()
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val random = Random()
    private var width = 0
    private var height = 0

    private val bubbleTexts = listOf(
        "爱跳舞", "有趣", "有生活情调", "有幽默感",
        "擅长摄影", "厨艺好", "善良", "温柔细心", "浪漫"
    )

    private val bubbleColors = listOf(
        Color.rgb(159, 185, 88), // 绿色
        Color.rgb(231, 123, 77), // 橙色
        Color.rgb(110, 151, 235), // 蓝色
    )

    init {
        // 初始化画笔
        textPaint.color = Color.WHITE
        textPaint.textSize = 24f
        textPaint.textAlign = Paint.Align.CENTER
        textPaint.typeface = Typeface.DEFAULT_BOLD

        // 设置背景为黑色
//        setBackgroundColor(Color.BLACK)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        width = w
        height = h

        // 创建气泡
        createBubbles()
    }

    private fun createBubbles() {
        bubbles.clear()
        bubbleTexts.forEachIndexed { index, text ->
            // 随机半径 (40-80)
            val radius = 80f + random.nextFloat() * 40f
            
            // 随机位置 (确保在视图范围内)
            val x = radius + random.nextFloat() * (width - 2 * radius)
            val y = radius + random.nextFloat() * (height - 2 * radius)
            
            // 随机速度 (-3到3之间)
            val dx = (random.nextFloat() * 6 - 3)
            val dy = (random.nextFloat() * 6 - 3)
            
            bubbles.add(
                BubbleBean(
                    text = text,
                    color = bubbleColors[index % bubbleColors.size],
                    x = x,
                    y = y,
                    radius = radius,
                    dx = if (dx == 0f) 1f else dx, // 确保不为0
                    dy = if (dy == 0f) 1f else dy
                )
            )
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        //绘制所有气泡（三层效果）
        bubbles.forEach { bubble ->
            //绘制底色
            paint.shader = RadialGradient(
                bubble.x, bubble.y, bubble.radius,
                bubble.color,
                bubble.color,
                Shader.TileMode.CLAMP
            )
            canvas.drawCircle(bubble.x, bubble.y, bubble.radius, paint)

            //1.内层核心（不透明，占半径50%）
            paint.shader = RadialGradient(
                bubble.x, bubble.y, bubble.radius * 0.7f,
                Color.argb(20, 255, 255, 255),
                Color.argb(20, 255, 255, 255),
                Shader.TileMode.CLAMP
            )
            canvas.drawCircle(bubble.x, bubble.y, bubble.radius * 0.9f, paint)

            //2.中层渐变（缓慢过度，50%-80%半径）
            paint.shader = RadialGradient(
                bubble.x, bubble.y, bubble.radius * 0.9f,
                Color.argb(20, 255, 255, 255),
                Color.argb(80, 255, 255, 255),
                Shader.TileMode.CLAMP
            )
            canvas.drawCircle(bubble.x, bubble.y, bubble.radius, paint)

            // 5. 绘制文字（自适应大小）
            textPaint.textSize = bubble.radius * 0.3f.coerceAtMost(36f)  // 限制最大36sp
            canvas.drawText(
                bubble.text,
                bubble.x,
                bubble.y + textPaint.textSize / 3,  // 垂直居中
                textPaint
            )
        }

        updateBubbles()
        invalidate()

    }

    private fun updateBubbles() {
        bubbles.forEach { bubble ->
            // 更新位置
            bubble.x += bubble.dx
            bubble.y += bubble.dy
            
            // 检测边界碰撞
            if (bubble.x - bubble.radius < 0 || bubble.x + bubble.radius > width) {
                bubble.dx = -bubble.dx
            }
            if (bubble.y - bubble.radius < 0 || bubble.y + bubble.radius > height) {
                bubble.dy = -bubble.dy
            }
            
            // 确保气泡在视图范围内
            bubble.x = bubble.x.coerceIn(bubble.radius, width - bubble.radius)
            bubble.y = bubble.y.coerceIn(bubble.radius, height - bubble.radius)
        }
        
        // 检测气泡之间的碰撞
        for (i in bubbles.indices) {
            for (j in i + 1 until bubbles.size) {
                val bubble1 = bubbles[i]
                val bubble2 = bubbles[j]
                
                // 计算距离
                val dx = bubble1.x - bubble2.x
                val dy = bubble1.y - bubble2.y
                val distance = sqrt(dx * dx + dy * dy)
                
                // 如果距离小于半径之和，则发生碰撞
                if (distance < bubble1.radius + bubble2.radius) {
                    // 简单碰撞响应 - 交换速度
                    val tempDx = bubble1.dx
                    val tempDy = bubble1.dy
                    bubble1.dx = bubble2.dx
                    bubble1.dy = bubble2.dy
                    bubble2.dx = tempDx
                    bubble2.dy = tempDy
                    
                    // 防止气泡重叠
                    val overlap = (bubble1.radius + bubble2.radius - distance) / 2f
                    val angle = atan2(dy, dx)
                    
                    bubble1.x += overlap * cos(angle)
                    bubble1.y += overlap * sin(angle)
                    bubble2.x -= overlap * cos(angle)
                    bubble2.y -= overlap * sin(angle)
                }
            }
        }
    }
}